package com.scan.bus;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.hello.scan.ScanCallBack;
import com.hello.scan.ScanTool;
import com.scan.bus.bean.DeviceContentEntity;
import com.scan.bus.bean.ScanMsgEntity;
import com.scan.bus.databinding.ActivityMainBinding;
import com.scan.bus.event.EventBusMessage;
import com.scan.bus.event.ScanResultMessage;
import com.scan.bus.event.ToastBusMessage;
import com.scan.bus.permission.PermissionListener;
import com.scan.bus.permission.PermissionsUtil;
import com.scan.bus.presenter.LocationListenerPresenter;
import com.scan.bus.util.Common;
import com.scan.bus.util.DeviceInfoUtil;
import com.scan.bus.util.LocationUtil;
import com.scan.bus.util.LogUtil;
import com.scan.bus.util.SharedPrefUtil;
import com.scan.bus.util.TimeUtil;
import com.scan.bus.view.IMainView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import cn.jpush.android.api.JPushInterface;

public class MainActivity extends BaseActivity implements ScanCallBack, IMainView {
    //权限数组（申请定位）
    private String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};

    private LocationListenerPresenter listenerPresenter;
//    private Queue<String> scanData = new LinkedList<>();

    private int scanCount = 0;
    private ActivityMainBinding mBinding;
    private SpeechUtils speechUtils;
    private long max_send_time = 60 * 60;
    private static final int WHAT_JPUSH = 1;//注册极光推送别名
    //    private static final int WHAT_QUEUE = 2;//请求扫码数据请提交请求
    private static final int WHAT_GETDEVICE_NEWWORK = 3;//获取班次信息并定时上报
    private static final int WHAT_SUBMIT_LOCALCODE = 4;//定时提交二维码信息
    private static final int WHAT_UPDATE_LOCTION = 5;//更新位置
    private static final int REQUEST_CODE_SCAN_ONE = 10001;
    private List<DeviceContentEntity> deviceContentEntity;

    @Override
    protected View getLayoutView() {
        mBinding = ActivityMainBinding.inflate(getLayoutInflater());
        return mBinding.getRoot();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void initData() {
        setStatusBarColor(R.color.white);
        setStatusBarFontDark();
        if (!DeviceInfoUtil.initScanTool(this, this)) {
//            Common.staticToast("该机型还没有适配");
        } else {
            ScanTool.GET.playSound(true);
        }

        EventBus.getDefault().register(this);
        mBinding.deviceNo.setText("设备号：" + SharedPrefUtil.getCacheSharedPrf("X-Device-ID", ""));
        speechUtils = new SpeechUtils();
        speechUtils.initTts(this);
        deviceContentEntity = new ArrayList<>();

        listenerPresenter = new LocationListenerPresenter(this, this, speechUtils);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            showGPSDisabledAlertToUser();
        }
        handler.sendEmptyMessageDelayed(WHAT_JPUSH, 3000);
        handler.sendEmptyMessageDelayed(WHAT_GETDEVICE_NEWWORK, 15000);
        handler.sendEmptyMessageDelayed(WHAT_SUBMIT_LOCALCODE, 30 * 60 * 1000);
        handler.sendEmptyMessageDelayed(WHAT_UPDATE_LOCTION, 0);
    }

    private void showGPSDisabledAlertToUser() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("请开启GPS定位服务")
                .setCancelable(false)
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Intent callGPSSettingIntent = new Intent(
                                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivity(callGPSSettingIntent);
                            }
                        });
        alertDialogBuilder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }

    @Override
    protected void initListener() {
        super.initListener();
        mBinding.init.setOnClickListener(this);
        mBinding.release.setOnClickListener(this);
        mBinding.initHuawei.setOnClickListener(this);
        mBinding.pauseReceiveData.setOnClickListener((this));
        mBinding.resumeReceiveData.setOnClickListener(this);
        //开启定位
        locatePremissrion();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.init:
                DeviceInfoUtil.initScanTool(this, this);
                break;
            case R.id.release:
                ScanTool.GET.release();
                break;
            case R.id.init_huawei:
                startActivityForResult(new Intent(MainActivity.this, ScanActivity.class), ScanActivity.REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY);
                break;
            case R.id.resume_receive_data:
                ScanTool.GET.pauseReceiveData();
                break;
            case R.id.device_no:
                ScanTool.GET.resumeReceiveData();
                break;
        }
    }

    /**
     * 获取位置权限信息
     */
    public void locatePremissrion() {
        PermissionsUtil.TipInfo tip = new PermissionsUtil.TipInfo("", "5", "9", "");
        PermissionsUtil.requestPermission(this, new PermissionListener() {
            @Override
            public void permissionGranted(@NonNull String[] permissions) {
                LocationUtil.initLocationOption(MainActivity.this, listenerPresenter);
            }

            @Override
            public void permissionDenied(@NonNull String[] permissions) {
                Common.staticToast(getString(R.string.permission_hint));
            }
        }, permissions, true, tip);
    }

    @Override
    public void onInitScan(boolean isSuccess) {
        //初始化社保的状态
    }

    /**
     * 2次扫码时间间隔
     */
    @Override
    public void onScanCallBack(String data) {
        onResult(data);
    }

    private void onResult(String data) {
        LogUtil.httpLogW("http" + "扫码回调数据 == > " + data);
        if (TextUtils.isEmpty(data)) return;
        String last_code = SharedPrefUtil.getCacheSharedPrf("last_code", "");
        if (listenerPresenter != null) {
            if (isEmpty(last_code) || !data.equals(last_code)) {
                listenerPresenter.updateCodeInfo(data);
            }
        }
        /**
         * 记录每天扫码数据
         */
        String dateTime = TimeUtil.getFormatTime(TimeUtil.FORMAT_YYY_MM_DD);
        String infoContent = SharedPrefUtil.getCacheSharedPrf(dateTime, "");
        if (!isEmpty(infoContent)) {
            infoContent = infoContent + "|" + data;
        } else {
            infoContent = data;
        }
        SharedPrefUtil.saveCacheSharedPrf(dateTime, infoContent);
    }

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WHAT_JPUSH:
                    if (!TextUtils.isEmpty(JPushInterface.getRegistrationID(MainActivity.this))) {
                        if (!MyApp.isSuccessResgiter) {
                            JPushInterface.setAlias(MainActivity.this, 0, SharedPrefUtil.getCacheSharedPrf("X-Device-ID", ""));
                            handler.sendEmptyMessageDelayed(WHAT_JPUSH, 3000);
                        }
                    } else {
                        JPushInterface.init(MainActivity.this);
                        handler.sendEmptyMessageDelayed(WHAT_JPUSH, 3000);
                    }

                    break;
                case WHAT_GETDEVICE_NEWWORK:
                    if (isEmpty(deviceContentEntity)) {
                        mBinding.tvCarName.setVisibility(View.GONE);
                        listenerPresenter.initDeviceInfo();
                    } else {
                        DeviceContentEntity currentCar = DeviceInfoUtil.getCurrentDeviceContent(deviceContentEntity);
                        if (currentCar != null && !isEmpty(currentCar.line_name)) {
                            mBinding.tvCarTitle.setVisibility(View.VISIBLE);
                            mBinding.tvCarName.setVisibility(View.VISIBLE);
                            String time_hh_mm = "";
                            if (currentCar.start_time.length() > 4) {
                                time_hh_mm = currentCar.start_time.substring(0, 5);
                            } else {
                                time_hh_mm = currentCar.start_time;
                            }
                            mBinding.tvCarTitle.setText(time_hh_mm + "-" + currentCar.driver_name);
                            mBinding.tvCarName.setText(currentCar.line_name);
                        } else {
                            mBinding.tvCarTitle.setVisibility(View.GONE);
                            mBinding.tvCarName.setVisibility(View.GONE);
                        }
                        handler.sendEmptyMessageDelayed(WHAT_GETDEVICE_NEWWORK, 60 * 1000);
                    }
                    break;
                case WHAT_SUBMIT_LOCALCODE://定时提交二维码
                    String dateTime = TimeUtil.getFormatTime(TimeUtil.FORMAT_YYY_MM_DD);
                    String infoContent = SharedPrefUtil.getCacheSharedPrf(dateTime, "");
                    if (!TextUtils.isEmpty(infoContent) && listenerPresenter != null) {
                        listenerPresenter.updateLocalCodeInfo(infoContent);
                    } else {
                        handler.sendEmptyMessageDelayed(WHAT_SUBMIT_LOCALCODE, 60 * 60 * 1000);
                    }
                    break;
                case WHAT_UPDATE_LOCTION:
                    if (LocationUtil.locationClient != null) {
                        LocationUtil.locationClient.requestLocation();
                    }
                    handler.sendEmptyMessageDelayed(WHAT_UPDATE_LOCTION, 0);
                    break;
                default:
//                    LogUtil.httpLogW("http"+"扫码队列数据值== > " + scanData.size());
//                    if(scanData.size()>0){
//                        listenerPresenter.updateCodeInfo(scanData.peek());
//                    }
                    break;
            }
        }
    };

    @Override
    public void localUpdownState(boolean isSuccess) {
        if (isSuccess) {
            String dateTime = TimeUtil.getFormatTime(TimeUtil.FORMAT_YYY_MM_DD);
            SharedPrefUtil.saveCacheSharedPrf(dateTime, "");//每小时上传一次本地扫码数据
            handler.sendEmptyMessageDelayed(WHAT_SUBMIT_LOCALCODE, 60 * 60 * 1000);//一小时后再次上传
        } else {
            handler.sendEmptyMessageDelayed(WHAT_SUBMIT_LOCALCODE, 5 * 60 * 1000);//5分钟后再次上传
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            LocationUtil.stopLocation();
            EventBus.getDefault().unregister(this);
            if (speechUtils != null) {
                speechUtils.ttsDestory();
            }
            if (ScanTool.GET != null)
                ScanTool.GET.release();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }

    /**
     * 上车或者失败的提示
     *
     * @param right
     */
    private void setState(boolean right) {
        mBinding.state.setVisibility(View.VISIBLE);
        mBinding.scanResult.setVisibility(View.VISIBLE);
        if (right) {
            mBinding.scanResult.setText("请上车");
            speechUtils.speakText("请上车");
        }
        mBinding.state.setImageDrawable(getResources().getDrawable(right ? R.drawable.right : R.drawable.error));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mBinding.state.setVisibility(View.GONE);
                    mBinding.scanResult.setVisibility(View.GONE);
                }
            }, 1000, 2000);
        }
    }

    /**
     * 扫码请求成功返回信息
     *
     * @param baseEntity
     */
    @Override
    public void scanStateShOW(boolean isSuccess, String msg, ScanMsgEntity baseEntity) {
//        if(scanData.size()>0){
//           scanData.poll();
//        }
//        handler.sendEmptyMessage(WHAT_QUEUE);
        mBinding.tips.postDelayed(new Runnable() {
            @Override
            public void run() {
                SharedPrefUtil.saveCacheSharedPrf("last_code", "");
            }
        }, 300);
        if (isSuccess) {
            setState(true);
        } else {
            if (!isEmpty(msg)) {
                speechUtils.speakText(msg);
                mBinding.scanResult.setText(msg);
            } else {
                return;
            }
            setState(false);
        }
        if (scanCount % 2 == 0) {
            mBinding.scanResult.setTextColor(Color.RED);
        } else {
            mBinding.scanResult.setTextColor(Color.BLUE);
        }
        scanCount++;
        mBinding.tips.setText(String.format(Locale.CHINA, "扫码次数：%d次", scanCount));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void dealReceiveMessage(EventBusMessage busMessage) {
        if (busMessage != null && speechUtils != null && speechUtils.textToSpeech != null) {
            speechUtils.speakText(busMessage.content);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void dealToastMessage(ToastBusMessage busMessage) {
        Toast.makeText(MainActivity.this, busMessage.content, Toast.LENGTH_LONG).show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void scanMessage(ScanResultMessage message) {
        onResult(message.content);
    }


    @Override
    public void initDeviceContent(List<DeviceContentEntity> deviceContent) {
        if (deviceContent.size() > 0) {
            deviceContentEntity.clear();
            deviceContentEntity.addAll(deviceContent);
            handler.sendEmptyMessageDelayed(WHAT_GETDEVICE_NEWWORK, 2 * 1000);
        } else {
            handler.sendEmptyMessageDelayed(WHAT_GETDEVICE_NEWWORK, 10 * 1000);
        }
    }
}